import { service } from '@vimi/utils-api'
import { fileSaveAs } from '@vimi/utils-tool'
/**
 * 获取pdf文档内容
 * @param {string} contractId 文档ID
 * @param {string} queryId 项目关联ID后端需要去查询直担或者联担
 * @returns arraybuffer
 */
export const getPdf = (contractId, queryId) => {
  const params = queryId
    ? { params: `"documentId=${contractId}"`, extra: queryId }
    : {
        params: `"documentId=${contractId}"`,
      }
  return service({
    method: 'GET',
    timeout: 0,
    url: '/api/credit/proxy/download/',
    params: {
      proxyKey: 'contract-doc-download',
      ...params,
    },
    responseType: 'arraybuffer',
  }).then(res => res.data)
}

export const downLoadPdf = (contractId, downName = '合同', quueryId) => {
  if (!contractId) {
    return Promise.resolve({})
  }
  return getPdf(contractId, quueryId)
    .then(data => {
      const blob = new Blob([data], { type: 'application/pdf' })
      const fileName = `${downName}.pdf`
      fileSaveAs(blob, fileName)
    })
    .catch(err => {
      this.$message.error(err)
    })
}

/**
 * 获取签章页面地址
 * @param {{
 *  contractId: string
 *  callbackPage: string
 *  tenantType: 'COMPANY' | 'PERSONAL'
 * }} param
 * @returns {string} signUrl
 */
export const getSignUrl = async ({
  contractId,
  callbackPage,
  tenantType = 'COMPANY',
  user,
  org,
}) => {
  const res = await service({
    method: 'POST',
    url: '/api/credit/proxy/',
    data: {
      proxy_key: 'signurl-query',
      params: JSON.stringify({
        contractId,
        tenantType,
        callbackPage,
        contact: user.phoneNumber,
        receiverName: user.realName,
        tenantName: org.orgName,
      }),
    },
  })
  if (res.data?.code === 0) {
    return res.data.signUrl
  }
  throw new Error(res.data)
}
